package org.rc.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import org.rc.dao.RaceDao;
import org.rc.dao.ResultDao;
import org.rc.model.Race;
import org.rc.six.DataStoreIndexDao;
import org.rc.six.Document;
import org.rc.six.IndexerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

/**
 * Re index race results {@link Race}
 * @author dokeeffe
 */
public class ReindexRacesTask extends Task {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReindexRacesTask.class);
    private RaceDao raceDao = new RaceDao();
    private ResultDao resultDao = new ResultDao();
    private IndexerService indexerService = new IndexerService(new DataStoreIndexDao());

    /**
     * Load all Results page by page and process 100 at a time.
     * Re index the race results by generating a {@link Document} for each result and passing to the {@link IndexerService}
     *
     * @param parameterMap
     */
    @Override
    public void run(Map parameterMap) {
        String cursor = getFirstArrayParam(parameterMap,"cursor");
        List<Race> results = new ArrayList<Race>();
        String newCursor = raceDao.getAllFromCursor(results, cursor, 100);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd");
        for (Race r : results) {
            Document doc = new Document("Race("+r.getId().toString()+")", r.getName(), sdf.format(r.getDate()));
            indexerService.index(doc);
        }
        if (!results.isEmpty()) {
            resubmit(newCursor);
        }
    }

    /**
     * Span a new task passing the cursor
     * @param newCursor
     */
    private void resubmit(String newCursor) {
        LOGGER.debug("spawning new indexer task");
        Queue queue = QueueFactory.getDefaultQueue();
        queue.add(withUrl("/admin?task="+getTaskName()+"&cursor=" + newCursor).method(TaskOptions.Method.GET));
    }

    @Override
    public String getUiName() {
        return "Reindex races";
    }

}
